//
//  YMEmoticonToolbar.swift
//  YMWeiBo
//
//  Created by mimi on 16/7/29.
//  Copyright © 2016年 mimi. All rights reserved.
//

import UIKit

private let tagNum = 2000

enum YMEmoticonToolbarType:Int {
    //按钮枚举
    case Default = 0
    case Emoji = 1
    case Lxh = 2
}


@available(iOS 9.0, *)
class YMEmoticonToolbar: UIStackView {
    
    //记录选中的button
    var currentButton: UIButton?
    
    //闭包
    var closure:((type:YMEmoticonToolbarType) ->())?
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI () {
        
        //设置排列方向
        axis = .Horizontal
        distribution = .FillEqually
        addChildButton("left", title: "默认", type: .Default)
        addChildButton("mid", title: "Emoji", type: .Emoji)
        addChildButton("right", title: "朗香花", type: .Lxh)
        
    }
    
    //MARK: 供外界调用的方法
    func setupCurrentButton(tag:Int){
        let button = viewWithTag(tag + tagNum) as! UIButton
        setupCurrentButtons(button)
    }
    //设置当前选中的button
    func setupCurrentButtons(button:UIButton) {
        
        if button == currentButton{
            return
        }
        /*
         01 把当前的button 状态改为false
         02 吧点击的button 状态改为true
         03 给当前的button赋值
         */
        currentButton?.selected = false
        button.selected = true
        currentButton = button
        
    }
    
    
    //MARK: button点击事件
    func buttonClick(button:UIButton) {
        setupCurrentButtons(button)
        closure?(type:YMEmoticonToolbarType(rawValue: button.tag - tagNum)!)
    }
    
    //MARK :添加button
    
    func addChildButton(imgName:String ,title:String ,type:YMEmoticonToolbarType) {
        let button = UIButton()
        if type == .Default{
            //MARK: pipi
           setupCurrentButtons(button)
        }
        
        button.tag = type.rawValue + tagNum
        
        //添加点击事件
        
        button.addTarget(self, action: #selector(YMEmoticonToolbar.buttonClick(_:)), forControlEvents: .TouchUpInside)
        //设置属性
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_selected"), forState: UIControlState.Selected)
    
        addArrangedSubview(button)
    }

}













